package cn.edu.hitwh.kanlema.controller;


import cn.edu.hitwh.kanlema.constant.UserConstants;
import cn.edu.hitwh.kanlema.dto.LoginFormDTO;
import cn.edu.hitwh.kanlema.dto.Result;
import cn.edu.hitwh.kanlema.dto.UserDTO;
import cn.edu.hitwh.kanlema.entity.UserInfo;
import cn.edu.hitwh.kanlema.service.IUserInfoService;
import cn.edu.hitwh.kanlema.service.IUserService;
import cn.edu.hitwh.kanlema.util.RegexPatterns;
import cn.edu.hitwh.kanlema.util.UserHolder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Pattern;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author vvcoder
 * @since 2025-8-18
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    @ApiOperation("发送手机验证码")
    public Result sendCode(
            @RequestParam("phone")
            @Pattern(regexp = RegexPatterns.PHONE_REGEX, message = "手机号格式错误")
            String phone
    ) {
        userService.sendCode(phone);
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    @ApiOperation("登录功能")
    public Result login(@RequestBody @Validated LoginFormDTO loginForm) {
        String token = userService.login(loginForm);
        return Result.ok(token);
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    @ApiOperation("登出功能")
    public Result logout(HttpServletRequest request) {
        userService.logout(request.getHeader(UserConstants.AUTH_HEADER));
        return Result.ok();
    }

    @GetMapping("/me")
    @ApiOperation("获取当前登录的用户信息")
    public Result me(){
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    @ApiOperation("根据用户id查询用户信息")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }
}
